package com.tma.intern;

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.jpedal.PdfDecoder;


public class ConvertImage {
		/**instance of PdfDecoder to convert PDF into image
		 * @throws org.jpedal.exception.PdfException */
	
		private byte[] file;
		private PdfDecoder decode_pdf = null;
		public ConvertImage(byte[] file) throws org.jpedal.exception.PdfException{
			this.file = file;
			decode_pdf = new PdfDecoder(true);
	    	//decode_pdf.openPdfFile(path); //file
			//decode_pdf.openPdfFile("C:/myPDF.pdf", "password"); //encrypted file
			decode_pdf.openPdfArray(file);
		}
		public int pageNumber(){
			return decode_pdf.getPageCount();
		}
		public void closeFile(){
			decode_pdf.closePdfFile();
		}
		public byte[] toImage(int page) {		
		/**set mappings for non-embedded fonts to use*/
		/**open the PDF file - can also be a URL or a byte array*/
		try {
				//decode_pdf.openPdfFileFromURL("http://www.mysite.com/myPDF.pdf",false);
				
		    	/**get page 1 as an image*/
		    	//page range if you want to extract all pages with a loop
		    	//int start = 1,  end = decode_pdf.getPageCount();
		    	BufferedImage buffImage=decode_pdf.getPageAsImage(page);
		    	ByteArrayOutputStream baos = new ByteArrayOutputStream();
				ImageIO.write( buffImage, "jpeg", baos );
				baos.flush();
				byte[] imageInByte = baos.toByteArray();
				baos.close();
				return imageInByte;
		} catch (Exception e) {
		    e.printStackTrace();
		    return null;
		}
	}
	

}